package com.zpark.controller;

import com.zpark.utils.JsonUtils;
import com.zpark.entity.Books;
import com.zpark.entity.User;
import com.zpark.service.IBooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @PackageName: com.zpark.controller
 * @ClassName: BooksController
 * @Description:
 * @author: RZS
 * @date: 2023/5/8  16:02
 */
@Controller
@RequestMapping("/book")
public class BooksController {

    @Autowired
    private IBooksService booksService;

    @RequestMapping("/login")
    public String login(HttpSession session, String uname, String pwd){
        User user = new User();
        user.setUname(uname);
        user.setPwd(pwd);
        // 假设登录成功
        session.setAttribute("user", user);

        return "books/index";
    }

    @RequestMapping("/index")
    public String getIndexPage(){
        return "books/index";
    }

    @RequestMapping("/toAddBook")
    public String getAddBookPage(){
        return "books/addBook";
    }

    // 添加books数据, 跳转到查询所有书籍页面
    @RequestMapping("/addBook")
    public String addBooks(Books books) {
        // 调用业务层添加书籍
        booksService.addBooks(books);
        // 重定向到查询所有book的Controller
        return "redirect:/book/allBook";
    }


    // 根据id删除books
    @RequestMapping("/deleteBook")
    public String delBooksById(Integer id){
        // 调用业务层方法
        booksService.delBooksById(id);

        return "redirect:/book/allBook";
    }

    // 跳转到修改页面
    @RequestMapping("/toUpdateBook")
    public ModelAndView getUpdatePage(Integer id){
        // 根据id查询数据
        Books book = booksService.findById(id);

        ModelAndView vm = new ModelAndView();
        vm.setViewName("books/updateBook");
        vm.addObject("book", book);

        return vm;
    }

    // 修改books
    @RequestMapping("/updateBook")
    public String changeBooksById(Books books){
        // 调用业务层方法
        booksService.changeBooksById(books);
        return "redirect:/book/allBook";
    }

    // 查询所有books
    @GetMapping("/allBook")
    public ModelAndView findAll(){
        ModelAndView vm = new ModelAndView();
        vm.setViewName("books/allBook");
        vm.addObject("books", booksService.findAll());

        return vm;
    }

    // 查询所有books
    @GetMapping("/allBook_Json")
    @ResponseBody
    public JsonUtils<List<Books>> findAllJson(){
        return new JsonUtils<>(20000, "OK", booksService.findAll());
    }

    // 根据books名字模糊查询books
    @RequestMapping("/queryBook")
    public ModelAndView findBooksByLikeName(String queryBookName){
        ModelAndView vm = new ModelAndView();
        vm.setViewName("books/allBook");
        vm.addObject("books", booksService.findBooksByLikeName(queryBookName));

        return vm;
    }

}
